import os, sys
sys.path.append(os.getcwd())
import time
import pandas as pd
import matplotlib.pyplot as plt
from contract_market.utils.api import xt_api
from contract_market.strategy.image.type import Action
import enum


def open_orders(verbose=False):
    '''
    return 
        price, quantity: [float], [float]
    '''
    orderbook = pd.DataFrame()
    for i in range(1, 10):
        order = xt_api.open_orders_api(symbol, page=i)
        if order and order.get('result') and order.get('result').get('items'):
            order = order.get('result').get('items')
            orderbook = pd.concat([orderbook, pd.DataFrame(order)])
        else:
            break
    maker = pd.DataFrame(columns=['price', 'quantity', 'side', 'id'])
    if not orderbook.empty:
        maker['price'] = orderbook.price.astype(float)
        maker['quantity'] = orderbook.origQty.astype(float)
        maker['side'] = orderbook.orderSide
        maker['id'] = orderbook.id.astype(int)
    if verbose:
        print('open_orders:', len(maker), len(maker[maker.side=='BUY']), len(maker[maker.side=='SELL']))
    time.sleep(3)
    return maker


def render_depth(is_save=True, is_show=False, verbose=False):
    while True:
        try:
            orders = xt_api.open_orders(symbol=symbol, method='api')
            long, short = orders[orders.side==Action.long].sort_values('price', ascending=False), \
                orders[orders.side==Action.short].sort_values('price', ascending=True)
            content = ''
            if is_save:
                with open('depth_stats.csv', 'a+') as fo:
                    long_content = f"{long.price.min()}, {long.price.max()}, {(long.price.max()-long.price.min())/long.price.min()}, {len(long)}, "
                    short_content = f"{short.price.min()}, {short.price.max()}, {(short.price.max()-short.price.min())/short.price.min()}, {len(short)}, "
                    compare_content = f"{(short.price.min()-long.price.max())/short.price.min()}"
                    content = long_content + short_content + compare_content + '\n'
                    fo.write(content)
            if verbose:
                print(content)
            if is_show:
                short = short.sort_values('price', ascending=True)
                long = long.sort_values('price', ascending=True)
                plt.close()
                plt.plot(short.price, short.quantity)   # .cumsum()
                plt.plot(long.price, long.quantity.to_numpy())  # [::-1].cumsum()[::-1]
                plt.pause(3)
        except Exception as ex:
            print(ex)


def balance():
    balance = xt_api.xt.get_coin_balance('usdt')
    balance = balance.get('result')
    print('balance', balance)
    return True


def position():
    '''
    "autoMargin": false,        //是否自动追加保证金    False       False
    "availableCloseSize": 0,    //可平仓数量（张）     47477       47477        Q1:availableCloseSize 可能等于 positionSize
    "closeOrderSize": 0,        //平仓挂单数量（张）    0           0
    "entryPrice": 0,            //开仓均价            0.427281    0.427285
    "isolatedMargin": 0,        //逐仓保证金          43815       20337        Q2: U本位单位是USDT, 币本位是USD (持仓保证金金额); 
                                                                                 isolatedMargin < openOrderMarginFrozen
    "leverage": 0,              //杠杆倍数            1           1
    "openOrderMarginFrozen": 0, //开仓订单保证金占用    33588       42495       Q3: 委托订单占用金额(成交导致与持仓金额不同，但是总量也不同)
    "positionSide": "",         //持仓方向            LONG        SHORT
    "positionSize": 0,          //持仓数量（张）       47477       47477
    "positionType": "",         //仓位类型            CROSSED     CROSSED
    "realizedProfit": 0,        //已实现盈亏          -8.06606    10.353525
    "symbol": ""                //交易对              xrp_usdt    xrp_usdt

    LONG
        持仓数量(个) = 持仓数量(张) * 合约面值 = 47477
        名义价值 = 持仓数量(个) * 价格
        开仓金额(U) = 逐仓保证金*杠杆率 = 43815
        持仓数量(个) = 开仓金额(U)/开仓均价=104321
        
        盈亏率=盈亏/保证金

    '''
    while True:
        try:
            pos = xt_api.position(symbol=symbol, method='api')
            print(pos)
            pos = pd.DataFrame(pos)
            long_pos = pos[pos.positionSide=='LONG']
            short_pos = pos[pos.positionSide=='SHORT']
            print('LONG', long_pos.entryPrice.squeeze(), long_pos.positionSize.squeeze())
            print('SHORT', short_pos.entryPrice.squeeze(), short_pos.positionSize.squeeze())
            with open('position_stats.csv', 'a+') as fo:
                fo.write(f'{long_pos.positionSize.squeeze()}, {short_pos.positionSize.squeeze()}\n')
        except:
            ...
        time.sleep(3)
    return True


if __name__ == '__main__':
    symbol = 'xrp_usdt'
    xt_api.init_client(symbol, 'um')

    render_depth()
    # position()
    # balance()
